
package com.ssh.interceptor;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.ssh.common.util.JsonResult;

public class MyActionErrorJSONValidationInterceptor  extends MethodFilterInterceptor {
		private static final long serialVersionUID = 1L;
	    static char[] hex = "0123456789ABCDEF".toCharArray();
	    private String rsCode="-1000";
	    private String rsDesc="";
	    private String fileUploadErrorCode ="-1"; 
	    private String exceedGlobUploadSize = "";//超过允许的最大文件大小
	    Long maxSize=1024*1024*2l;
	    private int oneM = 1048576;
	    Long actionFileUploadSize=1024*1024*2l;
	    public Long getActionFileUploadSize() {
			return actionFileUploadSize;
		}
		public void setActionFileUploadSize(Long actionFileUploadSize) {
			this.actionFileUploadSize = actionFileUploadSize;
		}
		public String getRsDesc() {
			return rsDesc;
		}
		public void setRsDesc(String rsDesc) {
			this.rsDesc = rsDesc;
		}
		public String getRsCode() {
			return rsCode;
		}
		public String getFileUploadErrorCode() {
			return fileUploadErrorCode;
		}
		public void setFileUploadErrorCode(String fileUploadErrorCode) {
			this.fileUploadErrorCode = fileUploadErrorCode;
		}
		@com.opensymphony.xwork2.inject.Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE)
	    public void setMaxSize(String maxSize) {
	        this.maxSize = Long.parseLong(maxSize); 
	    }
		/**
	     * 验证失败后的结果码，用配置文件载入，默认为-100
	     * @param rsCode
	     */
	    public void setRsCode(String rsCode){
	    	this.rsCode = rsCode;
	    }
	    @Override
	    protected String doIntercept(ActionInvocation invocation) throws Exception {
	        HttpServletResponse response = ServletActionContext.getResponse();
	        HttpServletRequest request = ServletActionContext.getRequest();
	        //if (!(request instanceof MultiPartRequestWrapper))//只处理文件上传的请求
	        Object action = invocation.getAction();
	        if(action instanceof ActionSupport){
	        	ActionSupport as =(ActionSupport)action;
	        	try{
		        	exceedGlobUploadSize =
		        		as.getText("struts.messages.error.file.too.large",new String []{actionFileUploadSize/oneM+"M"});
		        	if(rsDesc!=null&&rsDesc.startsWith("${getText(")){
		        		rsDesc = rsDesc = rsDesc.substring(11);
		        		rsDesc = rsDesc.substring(0,rsDesc.length()-3);
		        		rsDesc = as.getText(rsDesc,""); 
		        	}
	        	}catch(Exception e){
	        		e.printStackTrace();
	        	}
	        }
            if (action instanceof ValidationAware) {
                // 生成json
                ValidationAware validationAware = (ValidationAware) action;
                if (validationAware.hasActionErrors()) {//仅仅检查action错误，其他不检查并且有_符号的消息
                	response.setCharacterEncoding("UTF-8");
                	try{
                		String tmp =buildResponse(validationAware);
                		response.getWriter().print("{\"jr\":"+tmp+"}");
                	}catch(Exception e){//系统不期望的异常，如果发生，需要进行调试排除
                		 JsonResult jr = new JsonResult();
                		 //jr.setRsCode("-9999");
                		 //jr.setRsDesc("unexpected system error occured!please email the system manager(heiquangogo@gmail.com) "); 
                		 JSONObject json = JSONObject.fromObject(jr);
                		response.getWriter().print("{\"jr\":"+json.toString()+"}");
                	}
                    response.setContentType("application/json");
                    return Action.NONE;
                }else{
                	return invocation.invoke();//没有错误时候
                }
            }else{
            	return invocation.invoke();//无验证文件时候
            }
	    }

	    /**
	     * @return JSON string that contains the errors and field errors
	     */
	    @SuppressWarnings("unchecked")
	    protected String buildResponse(ValidationAware validationAware) {
	    	JsonResult jr = new JsonResult();
	    	/*if(jr.getVerboseCodeDesc()==null)jr.setVerboseCodeDesc(new HashMap());
	        if (validationAware.hasErrors()) {
	            //action错误
	            if (validationAware.hasActionErrors()) {
		        	jr.setRsCode(rsCode);//验证总错误代码
		        	jr.setRsDesc(rsDesc);
	            	buildArray(validationAware.getActionErrors(),jr);
	            }
	        }*/
	        JSONObject json = JSONObject.fromObject(jr);
	        return json.toString();
	    }
	    
	    private void buildArray(Collection<String> values,JsonResult jr) {
	        for (String value : values) {
	            //对于comm-upload抛出的异常进行改装，使其符合国际化 
	            if(value.indexOf("exceeds the configured maximum")>=0){
	            	value=this.exceedGlobUploadSize;
	            }
	            //对value进行json解析 ,存在{符号
	            int index = value.indexOf("_");
	            if(index>=0){
			            try{
			            	/*String c = value.substring(0,index);
			            	String m = value.substring(index+1,value.length());
			            	List l = jr.getVerboseCodeDesc().get(c);
			            	if(l==null){
			            		l = new ArrayList();
			            		jr.getVerboseCodeDesc().put(c,l);
			            	}
			            	l.add(m);*/
			            }catch(Exception e){
			            	e.printStackTrace();
			            }
	            } else{//add by laohuidi at 9/17/2010 12:32
	            	 // jr.setRsDesc(jr.getRsDesc()+" "+value);
			       }
	        }
	    }
	    protected boolean useActionMessageBundle;
	    public void setUseActionMessageBundle(String value) {
	        this.useActionMessageBundle = Boolean.valueOf(value);
	    }

	}

